package edu.zju.gis.dldsj.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用于进行用户登录状态验证
 *
 * @author yanlo yanlong_lee@qq.com
 * @version 1.0 2018/08/15
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    private final static String SESSION_KEY = "userName";

    @Bean
    public SecurityInterceptor getSecurityInterceptor() {
        return new SecurityInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());

        addInterceptor.excludePathPatterns("/error");
        addInterceptor.excludePathPatterns("/user/login**");

        addInterceptor.addPathPatterns("/**");
    }

    private static class SecurityInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
            HttpSession session = request.getSession();
            //todo to be removed
            session.setAttribute(SESSION_KEY, "ubt");
            session.setAttribute("userId", "1");
            session.setAttribute("roleId", "1");
            session.setAttribute("fullName", "ubt@ubt1");
            if (session.getAttribute(SESSION_KEY) != null) {
                return true;
            } else {
                response.sendRedirect("/login");//todo 待更改为消息，而非页面
                return false;
            }
        }
    }
}
